const { LinValidator, Rule } = require('../../core/lin-validator-v2')
const { User } = require('../models/User')

class RegisterValidator extends LinValidator {
  constructor() {
    super()
    // 注册时id不用提供
    // this.id = [
    //   new Rule('isInt', 'id必须是正整数', {min: 1})
    // ]
    this.userName = [
      new Rule('isLength', '用户名必须是2-32个字符', {
          min: 2,
          max: 32
      })
    ]
    this.password = [
      new Rule('isLength', '密码至少6个字符，最多32个字符', {
        min: 6,
        max: 32
      }),
      new Rule('matches', '密码要同时包含数字和字母', '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]')
    ]
    this.confirmPassword = this.password
  }

  validatePassword(vals) { // 自定义的验证器必须以validate开头
    const psw1 = vals.body.password
    const psw2 = vals.body.confirmPassword
    if (psw1 !== psw2) {
      throw new Error('密码和确认密码必须相同')
    }
  }

  async validateUserName(vals) { // 用户名是唯一的，验证是否存在同名的用户
    const uName = vals.body.userName
    if(!uName) throw new Error('请提供用户名')
    const user = await User.findOne({where: { userName: uName }})
    if(user) {
      throw new Error(`用户名${uName}已经存在`)
    }
  }
}

module.exports = {
  RegisterValidator
}